/**
 * @param {number[][]} fruits
 * @param {number} startPos
 * @param {number} k
 * @return {number}
 */
 var maxTotalFruits = function(fruits, startPos, k) {
  const g = {}, arr = fruits.map(v => v[0])
  for(let [x, y] of fruits){
    g[x] = y
  }
  const map = new Map().set(fruits[0][0], fruits[0][1])
  let sum = fruits[0][1]
  for(let i = 1; i<fruits.length; i++){
    let [x, y] = fruits[i]
    sum += y
    map.set(x, sum)
  }
  const searchLeft = (i) => {
    let l = 0, r = arr.length
    while(l < r){
      let m = (l + r) >> 1
      if(arr[m] >= i){
        r = m
      }else{
        l = m+1
      }
    }
    return arr[l]
  }
  const searchRight = (i) => {
    let l = 0, r = arr.length
    while(l <= r){
      let m = (l + r) >> 1
      if(arr[m] <= i){
        l = m+1
      }else{
        r = m-1
      }
    }
    return arr[r]
  }
  const getSum = (l, r) => {
    let left = searchLeft(l), right = searchRight(r)
    return map.get(right) - map.get(left) + g[left]
  }
  let ans = 0
  for(let l = Math.max(0, startPos-k); l<=startPos; l++){
    let r = Math.max(l + k - (startPos - l),startPos)
    ans = Math.max(ans, getSum(l,r) || 0)
  }
  return ans
};